package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.*;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.BooleanResDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageHelperUtils;
import com.jzo2o.mysql.utils.PageUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {


    @Resource
    MapApi mapApi;
    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();

        LambdaQueryWrapper<AddressBook> query =
                addressBookLambdaQueryWrapper.eq(AddressBook::getUserId, userId).eq(AddressBook::getCity, city);
        List<AddressBook> addressBooks = baseMapper.selectList(query);

        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    @Override
    @Transactional
    public void addAddressBook(AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        if (StringUtils.isEmpty(addressBookUpsertReqDTO.getAddress())) {
            throw new RuntimeException("地址不能为空");
        }
        if (StringUtils.isEmpty(addressBookUpsertReqDTO.getCity())) {
            throw new RuntimeException("城市不能为空");
        }
        if (StringUtils.isEmpty(addressBookUpsertReqDTO.getCounty())) {
            throw new RuntimeException("县不能为空");
        }
        if (StringUtils.isEmpty(addressBookUpsertReqDTO.getPhone())) {
            throw new RuntimeException("手机号不能为空");
        }
        if (StringUtils.isEmpty(addressBookUpsertReqDTO.getProvince())) {
            throw new RuntimeException("省份不能为空");
        }
        if (StringUtils.isEmpty(addressBookUpsertReqDTO.getName())) {
            throw new RuntimeException("名称不能为空");
        }
        if (StringUtils.isEmpty(addressBookUpsertReqDTO.getLocation())) {
            throw new RuntimeException("经纬度不能为空");
        }
        AddressBook addressBook = BeanUtils.toBean(addressBookUpsertReqDTO,
                AddressBook.class);
        addressBook.setUserId(UserContext.currentUserId());

        if (addressBookUpsertReqDTO.getIsDefault().equals(1)) {
            LambdaUpdateWrapper<AddressBook> addressBookLambdaUpdateWrapper =
                    new LambdaUpdateWrapper<>();

            LambdaUpdateWrapper<AddressBook> query = addressBookLambdaUpdateWrapper
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .eq(AddressBook::getIsDefault, 1)
                    .set(AddressBook::getIsDefault, 0);
            int update = baseMapper.update(null, query);
            if (update<=0) {
                throw new RuntimeException("设置默认地址失败");
            }
        }

        //注意少了一个经纬度的判断，因为文档是这个是不必要的。
        if (Objects.isNull(addressBookUpsertReqDTO.getLocation())) {
            String completeAddress =addressBookUpsertReqDTO.getProvince()
                    +addressBookUpsertReqDTO.getCounty()
                    +addressBookUpsertReqDTO.getCity()
                    +addressBookUpsertReqDTO.getAddress();
            LocationResDTO locationByAddress = mapApi.getLocationByAddress(completeAddress);
            addressBook.setLon(Double.parseDouble(locationByAddress.getLocation().split(",")[0]));
            addressBook.setLat(Double.parseDouble(locationByAddress.getLocation().split(",")[1]));
        }

        String[] split = addressBookUpsertReqDTO
                .getLocation().split(",");
        addressBook.setLon(Double.parseDouble(split[0]));
        addressBook.setLat(Double.parseDouble(split[1]));

        //另一种写法
//        addressBook.setLon(NumberUtils.parseDouble(split[0]));
//        addressBook.setLat(NumberUtils.parseDouble(split[1]));
        baseMapper.insert(addressBook);

    }



    @Override
    public AddressBookResDTO getAddressBookDetailById(Long id) {
        AddressBook addressBook = baseMapper.selectById(id);
        return BeanUtils.toBean(addressBook, AddressBookResDTO.class);

    }

    @Override
    @Transactional
    public void updateAddressBook(AddressBookUpsertReqDTO addressBookUpsertReqDTO, Long id) {
        if (Objects.equals(addressBookUpsertReqDTO.getIsDefault(),1L)) {
            //把之前的默认地址取消掉
            LambdaUpdateWrapper<AddressBook> objectLambdaUpdateWrapper =
                    new LambdaUpdateWrapper<>();
            LambdaUpdateWrapper<AddressBook> query =
                    objectLambdaUpdateWrapper.eq(AddressBook::getUserId, UserContext.currentUserId())
                            .eq(AddressBook::getIsDefault, 1)
                            .set(AddressBook::getIsDefault, 0);
            baseMapper.update(null, query);
        }
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(addressBookUpsertReqDTO,addressBook);
        addressBook.setId(id);
        //调用第三方，根据地址获取经纬度坐标
        String completeAddress = addressBookUpsertReqDTO.getProvince() +
                addressBookUpsertReqDTO.getCity() +
                addressBookUpsertReqDTO.getCounty() +
                addressBookUpsertReqDTO.getAddress();
        //远程请求高德获取经纬度
        LocationResDTO locationDto = mapApi.getLocationByAddress(completeAddress);
        //经纬度(字符串格式：经度,纬度),经度在前，纬度在后
        String location = locationDto.getLocation();
        if(StringUtils.isNotEmpty(location)) {
            // 经度
            addressBook.setLon(NumberUtils.parseDouble(locationDto.getLocation().split(",")[0]));
            // 纬度
            addressBook.setLat(NumberUtils.parseDouble(locationDto.getLocation().split(",")[1]));
        }

//下面自己写的有问题，是自己得组装成新的去更新,经纬度也得是新的
//        AddressBook addressBook1 = baseMapper.selectById(id);
//        BeanUtils.copyProperties(addressBook1,addressBook);
//        BeanUtils.copyProperties(addressBookUpsertReqDTO,addressBook);
//        addressBook.setUpdateTime(LocalDateTime.now());
//        if (!(StringUtils.isEmpty(addressBookUpsertReqDTO.getLocation()))) {
//            String[] split = addressBookUpsertReqDTO.getLocation().split(",");
//            addressBook.setLon(Double.parseDouble(split[0]));
//            addressBook.setLat(Double.parseDouble(split[1]));
//        }
        //todo 这里要确定一下实体类中  @TableField(fill = FieldFill.INSERT_UPDATE)
        //    private Long updateBy;会不会自动注入
//        addressBook.setUpdateBy(UserContext.currentUserId());
        baseMapper.updateById(addressBook);
    }

    @Override
    @Transactional
    public void batchDeleteAddressBook(List<Long> ids) {
        if (CollUtils.isEmpty(ids)) {
            throw new RuntimeException("请选择要删除的记录");
        }
        for (int i = 0; i < ids.size(); i++) {
            long id = ids.get(i);
            int i1 = baseMapper.deleteById(id);
            if (i1<=0) {
                throw new RuntimeException("第"+(i1+1)+"条删除失败");
            }
        }

    }

    @Override
    public void setDefaultAddress(Long flag, Long id) {
        if (!Objects.equals(flag,1L)&&!Objects.equals(flag,0L)) {
            throw new RuntimeException("flag参数错误");
        }
        //下面这种比较flag!=1L会导致空指针异常，改成flag.equals(1L)
//        if (flag!=1L&&flag!=0L) {
//            throw new RuntimeException("flag参数错误");
//        }
        AddressBook newAddressBook = new AddressBook();
        AddressBook addressBook = baseMapper.selectById(id);
        BeanUtil.copyProperties(addressBook,newAddressBook);
        if (Objects.equals(flag,1L)&&Objects.equals(addressBook.getIsDefault(),0L)) {
            //把之前的默认地址取消掉
            LambdaUpdateWrapper<AddressBook> objectLambdaUpdateWrapper =
                    new LambdaUpdateWrapper<>();
            LambdaUpdateWrapper<AddressBook> query =
                    objectLambdaUpdateWrapper.eq(AddressBook::getUserId, UserContext.currentUserId())
                            .eq(AddressBook::getIsDefault, 1)
                            .set(AddressBook::getIsDefault, 0);
            baseMapper.update(null, query);
            //设置新的默认地址
            newAddressBook.setIsDefault(1);
            baseMapper.updateById(newAddressBook);
        }else if(Objects.equals(flag,0L)&&Objects.equals(addressBook.getIsDefault(),1L)){
            newAddressBook.setIsDefault(0);
            baseMapper.updateById(newAddressBook);
        }
    }

    @Override
    public AddressBookResDTO getDefaultAddress() {
        LambdaQueryWrapper<AddressBook> query =
                new LambdaQueryWrapper<>();
        LambdaQueryWrapper<AddressBook> eqQuery =
                query.eq(AddressBook::getUserId, UserContext.currentUserId())
                .eq(AddressBook::getIsDefault, 1);
        AddressBook addressBook = baseMapper.selectOne(eqQuery);

        AddressBookResDTO addressBookResDTO = new AddressBookResDTO();
        BeanUtil.copyProperties(addressBook,addressBookResDTO);
        return addressBookResDTO;



    }

    @Override
    public PageResult<AddressBookResDTO> pageAddressBook(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
        Page<AddressBook> page = PageUtils.parsePageQuery(addressBookPageQueryReqDTO, AddressBook.class);
        LambdaQueryWrapper<AddressBook> query =
                new LambdaQueryWrapper<>();
        LambdaQueryWrapper<AddressBook> eq =
                query.eq(AddressBook::getUserId,
                        UserContext.currentUserId());
        Page<AddressBook> addressBookPage =
                baseMapper.selectPage(page, eq);
        return PageUtils.toPage(addressBookPage, AddressBookResDTO.class);

    }
}
